package com.sumfun.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sumfun.blog.annotation.RequireLogin;
import com.sumfun.blog.common.BaseResponse;
import com.sumfun.blog.common.ErrorCode;
import com.sumfun.blog.common.ResultUtils;
import com.sumfun.blog.exception.BusinessException;
import com.sumfun.blog.model.domain.Article;
import com.sumfun.blog.model.dto.ArticleQueryDTO;
import com.sumfun.blog.model.request.ArticleAddRequest;
import com.sumfun.blog.model.request.ArticleQueryRequest;
import com.sumfun.blog.model.request.ArticleUpdateRequest;
import com.sumfun.blog.service.ArticleService;
import com.sumfun.blog.utils.LoginUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 文章Controller
 * ;'
 *
 * @author sumfun
 * @date 2024-04-21
 */
@ApiOperation(value = "文章信息Controller", tags = {"文章信息"})
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @RequireLogin
    @PostMapping("/add")
    public BaseResponse<Long> addArticle(@RequestBody ArticleAddRequest articleAddRequest, HttpServletRequest request) {
        if (articleAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long articleId = articleService.addArticle(articleAddRequest);
        return ResultUtils.success(articleId);
    }

    @RequireLogin
    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> deleteArticle(@PathVariable Long id, HttpServletRequest request) {
        if (id == null || id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean res = articleService.removeById(id);
        return ResultUtils.success(res);
    }

    @RequireLogin
    @PostMapping("/update")
    public BaseResponse<Boolean> updateArticle(@RequestBody ArticleUpdateRequest articleUpdateRequest, HttpServletRequest request) {
        if (articleUpdateRequest == null || articleUpdateRequest.getArticleId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean res = articleService.updateArticle(articleUpdateRequest);
        return ResultUtils.success(res);
    }

    @GetMapping("/get")
    public BaseResponse<Article> getArticleById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Article article = articleService.getById(id);
        return ResultUtils.success(article);
    }

    @GetMapping("/list")
    public BaseResponse<List<Article>> getArticleList(ArticleQueryRequest articleQueryRequest, HttpServletRequest request) {
        if (articleQueryRequest == null) {
            List<Article> articleList = articleService.list();
            return ResultUtils.success(articleList);
        }

        boolean allOtherFieldsAreEmpty = true;
        // 但由于我们不知道具体的字段，这里使用反射来检查（注意：反射可能会影响性能）
        for (java.lang.reflect.Field field : articleQueryRequest.getClass().getDeclaredFields()) {
            field.setAccessible(true); // 允许访问私有字段
            try {
                if (!"pageSize".equals(field.getName()) && !"pageNum".equals(field.getName()) && field.get(articleQueryRequest) != null) {
                    allOtherFieldsAreEmpty = false;
                    break;
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

        List<Article> articleList;
        if (allOtherFieldsAreEmpty) {
            // 如果其他字段都为空，则查询所有记录
            articleList = articleService.list();
        } else {
            // 否则，根据查询请求构建查询条件并查询
            Article article = new Article();
            BeanUtils.copyProperties(articleQueryRequest, article);
            QueryWrapper<Article> queryWrapper = new QueryWrapper<>(article);
            // 如果需要分页，可以在这里设置 queryWrapper.last("LIMIT #{pageSize} OFFSET #{pageNum * pageSize}")
            // 但通常 MyBatis Plus 的分页插件会处理这些，确保您已经配置了分页插件
            articleList = articleService.list(queryWrapper);
        }

        return ResultUtils.success(articleList);
    }

    //
    @PostMapping("/list/page")
    public BaseResponse<Page> getArticleListByPage(@RequestBody ArticleQueryRequest articleQueryRequest) {
        if (articleQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<ArticleQueryDTO> pageResult = articleService.getPageList(articleQueryRequest);
        return ResultUtils.success(pageResult);
    }
}
